<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader @addtext="addfn" :arr="list"></TodoHeader>
    <TodoMain :lists="showarr" @shanchu="splicefn"> </TodoMain>
    <TodoFooter :farr='showarr'  :getSel="getSel" @changeType="typeFn" @clear="clearfn"></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css";
import "./styles/index.css";

import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list:JSON.parse(localStorage.getItem('todoList'))||[],
      // list: [
      //   { id: 100, name: "吃饭", isDone: true },
      //   { id: 101, name: "睡觉", isDone: false },
      //   { id: 102, name: "打豆豆", isDone: true },
      // ],
      getSel:'all'
    };
  },
  methods: {
    addfn(text) {
      this.list.push({
        id: this.list.at(-1) ? this.list.at(-1).id + 1 : 100,
        name: text,
        isDone: false,
      });
    },
    splicefn(id) {
      let index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    typeFn(type){
this.getSel = type
    },
    //清空已完成的
    clearfn(){
this.list=this.list.filter(item=>item.isDone==false)
    }
  },
  //定义showarr数组通过list 条件筛选而来
  computed:{
    showarr(){
        if (this.getSel === 'yes') {//显示已完成
        return this.list.filter((item) => item.isDone)
      }
      if (this.getSel === 'no') {//显示未完成
        return this.list.filter((item) => !item.isDone)
      }//全部显示
      return this.list
    }
  },
  //数据缓存
  // watch监听数组  本地存储
  watch:{
    list:{
      deep:true,
      handler(){
        //只要list变化 覆盖式保存到locaStorage里
        localStorage.setItem('todoList',JSON.stringify(this.list))

      }
    }
  }
};
</script>